package com.mbcn.dao.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.googlecode.s2hibernate.struts2.plugin.annotations.SessionTarget;
import com.googlecode.s2hibernate.struts2.plugin.annotations.TransactionTarget;
import com.mbcn.dao.ItemDetailsDAO;
import com.mbcn.model.Item;
import com.mbcn.model.Member;
import com.mbcn.pageModel.ItemDetails;
import com.mbcn.system.commonUtil.Util;
import com.mbcn.system.hibernateUtil.HibernateUtil;

public class ItemDetailsDAOImpl implements ItemDetailsDAO {
	@SessionTarget
	Session session;
	     
	@TransactionTarget
	Transaction transaction;
	HttpServletRequest request = ServletActionContext.getRequest();
	
	public ItemDetails loadItemDetails(Integer itemId) {
		ItemDetails itemDetails = new ItemDetails();
		try {
		session = HibernateUtil.getSessionFactory().openSession();
		transaction = session.beginTransaction();
		String hql = "SELECT * FROM item I INNER JOIN member M ON i.memberId = M.memberId WHERE I.itemId=:itemId";
        Query query = session.createSQLQuery(hql).addEntity(Member.class).addEntity(Item.class).setParameter("itemId",itemId);
        Object[] object = (Object[]) query.uniqueResult();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    		Date itemDatePost = formatter.parse(Util.getValueFromObject(object[1], "itemDatePost"));
    		
        itemDetails.setMemberNm(Util.getValueFromObject(object[0], "memberNm"));
        itemDetails.setMemberAvt(Util.getValueFromObject(object[0], "memberAvt"));
        itemDetails.setItemTitle(Util.getValueFromObject(object[1], "itemTitle"));
        itemDetails.setItemId(Integer.parseInt(Util.getValueFromObject(object[1], "itemId")));
        itemDetails.setItemCategory(Integer.parseInt(Util.getValueFromObject(object[1], "itemCategory")));
        itemDetails.setItemContent(Util.getValueFromObject(object[1], "itemContent"));
        itemDetails.setItemDatePost(itemDatePost);
        itemDetails.setItemImage(Util.getValueFromObject(object[1], "itemImage"));
        itemDetails.setItemStatus(Integer.parseInt(Util.getValueFromObject(object[1], "itemStatus")));
        itemDetails.setMemberId(Integer.parseInt(Util.getValueFromObject(object[1], "memberId")));
        
        
		transaction.commit();
		session.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return itemDetails;
	}

}
